﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.Text;
using Com.Becom.CommonLibrary.Db.AdoNet;

public partial class AjaxProcessData : System.Web.UI.Page
{
    #region 属性
    private string flag = string.Empty;
    private string tableName = string.Empty;
    private Dictionary<string, string> dictFields = null;
    private Dictionary<string, string> dictWheres = null;
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetXMLDoc();
            ProcessData();

        }
    }

    private void GetXMLDoc()
    {
        XmlDocument xmlIn = new XmlDocument();
        xmlIn.Load(Request.InputStream);

        XmlNode nodeFlag = xmlIn.SelectSingleNode("//Flag");
        if (nodeFlag != null)
        {
            flag = nodeFlag.InnerText;
        }

        XmlNode nodeTable = xmlIn.SelectSingleNode("//Table");
        if (nodeTable != null)
        {
            tableName = nodeTable.InnerText;
        }

        XmlNode nodeData = xmlIn.SelectSingleNode("//Data");
        if (nodeData != null)
        {
            XmlNodeList nodeChildData = nodeData.ChildNodes;
            dictFields = new Dictionary<string, string>();
            foreach (XmlNode node in nodeChildData)
            {
                dictFields.Add(node.Name, node.InnerText);
            }
        }

        XmlNode nodeWhere = xmlIn.SelectSingleNode("//Where");
        if (nodeWhere != null)
        {
            XmlNodeList nodeChildWhere = nodeWhere.ChildNodes;
            dictWheres = new Dictionary<string, string>();
            foreach (XmlNode node in nodeChildWhere)
            {
                dictWheres.Add(node.Name, node.InnerText);
            }
        }

    }


    private void ProcessData()
    {
        if (string.IsNullOrEmpty(flag) || string.IsNullOrEmpty(tableName))
        {
            return;
        }

        bool successFlag = false;
        string strReturnXml = string.Empty;
        try
        {
            if (flag == "0")
            {
                int part_id = Insert();
                if (part_id != 0)
                {
                    successFlag = true;
                }
                strReturnXml = string.Format("<?xml version='1.0' encoding='GB2312'?><Return><SuccessFlag>{0}</SuccessFlag><part_id>{1}</part_id></Return>", successFlag, part_id);
            }
            else if (flag == "1")
            {
                successFlag = Update();
                strReturnXml = string.Format("<?xml version='1.0' encoding='GB2312'?><SuccessFlag>{0}</SuccessFlag>", successFlag);
            }
            else if (flag == "2")
            {
                successFlag = Delete();
                strReturnXml = string.Format("<?xml version='1.0' encoding='GB2312'?><SuccessFlag>{0}</SuccessFlag>", successFlag);
            }
            //else if (flag == "3")  //获取某科目对应的评价
            //{
            //    DataSet dsAppraisalOfSubject = GetSubjectAppraisal();
            //    strReturnXml = GetXMLOfSubjectAppraisal(dsAppraisalOfSubject);
            //}

            this.Response.Write(strReturnXml);
            this.Response.End();
        }
        catch (Exception ex)
        {
        }
        finally
        {
        }

    }



    private int Insert()
    {

        if (dictFields == null || dictFields.Count <= 0)
        {
            throw new Exception("参数不正确");
        }

        StringBuilder sbFields = new StringBuilder("(");
        StringBuilder sbData = new StringBuilder("(");

        foreach (KeyValuePair<string, string> field in dictFields)
        {
            sbFields.AppendFormat("{0},", field.Key);
            string value = string.Empty;
            if (string.Compare(field.Key, "createDate", true) != 0)
            {
                value = field.Value;
            }
            else
            {
                value = "'" + DateTime.Now.ToString() + "'";
            }
            sbData.AppendFormat("  {0},", value);
        }
        sbFields.Replace(",", " ", sbFields.Length - 1, 1);
        sbData.Replace(",", " ", sbData.Length - 1, 1);
        sbFields.Append(")");
        sbData.Append(")");

        StringBuilder sbSql = new StringBuilder();
        sbSql.AppendFormat("insert into {0}  ", tableName);
        sbSql.Append(sbFields);
        sbSql.Append(" values ");
        sbSql.Append(sbData);
        sbSql.Append(";select @@IDENTITY");


        object obj = SqlHelper.ExecuteNonQuery(CommandType.Text, sbSql.ToString());
        if (obj != null)
        {
            return Convert.ToInt32(obj);
        }
        else
        {
            return 0;
        }
    }

    private bool Update()
    {
        if (dictFields == null || dictFields.Count <= 0)
        {
            return false;
        }

        if (dictWheres == null || dictWheres.Count <= 0)
        {
            return false;
        }

        StringBuilder sbData = new StringBuilder();
        LinkString(dictFields, ",", ref sbData);

        StringBuilder sbWhere = new StringBuilder();
        LinkString(dictWheres, "and", ref sbWhere);

        StringBuilder sbSql = new StringBuilder();
        sbSql.AppendFormat("update {0} set ", tableName);
        sbSql.Append(sbData);
        sbSql.Append(" where ");
        sbSql.Append(sbWhere);

        int ret = SqlHelper.ExecuteNonQuery(CommandType.Text, sbSql.ToString());
        return true;

    }

    private bool Delete()
    {
        if (dictWheres == null || dictWheres.Count <= 0)
        {
            return false;
        }

        StringBuilder sbFields = new StringBuilder();
        StringBuilder sbData = new StringBuilder();

        foreach (KeyValuePair<string, string> field in dictFields)
        {
            sbFields.AppendFormat("{0}=", field.Key);
            string value = string.Empty;
            //if (string.Compare(field.Key, "createDate", true) != 0)
            //{
            //    value = field.Value;
            //}
            //else
            //{
            //    value = "'" + DateTime.Now.ToString() + "'";
            //}
            sbData.AppendFormat("  {0} and ", value);
        }
        sbFields.Replace(",", " ", sbFields.Length - 1, 1);
        sbData.Replace(",", " ", sbData.Length - 1, 1);
     

        StringBuilder sbSql = new StringBuilder();
        sbSql.AppendFormat("delete from {0}  ", tableName);
        sbSql.Append(sbFields);
        sbSql.Append(" values ");
        sbSql.Append(sbData);
        sbSql.Append(";select @@IDENTITY");


        object obj = SqlHelper.ExecuteNonQuery(CommandType.Text, sbSql.ToString());
        //if (obj != null)
        //{
        //    return Convert.ToInt32(obj);
        //}
        //else
        //{
        //    return 0;
        //}


        return false;
    }


    //    private bool Delete()
    //    {
    //        if (dictWheres == null || dictWheres.Count <= 0)
    //        {
    //            return false;
    //        }

    //        List<string> listSqls = new List<string>();
    //        StringBuilder sbSql = new StringBuilder();
    //        StringBuilder sbWhere = new StringBuilder();
    //        string strSql = string.Empty;

    //        LinkString(dictWheres, "and", ref sbWhere);

    //        int part_id = 0;
    //        //删除相应的附件
    //        if (string.Compare(tableName, "partinfo", true) == 0)
    //        {

    //            foreach (KeyValuePair<string, string> kv in dictWheres)
    //            {
    //                if (string.Compare(kv.Key, "part_id", true) == 0)
    //                {
    //                    part_id = int.Parse(kv.Value);
    //                    break;
    //                }
    //            }
    //            //删除硬盘上的附件
    //            DelectAttachmentFiles(part_id);

    //            strSql = string.Format("delete from attachment where {0}", sbWhere);
    //            listSqls.Add(strSql);
    //        }
    //        else if (string.Compare(tableName, "attachment", true) == 0)
    //        {
    //            int attachment_id = 0;
    //            foreach (KeyValuePair<string, string> kv in dictWheres)
    //            {
    //                if (string.Compare(kv.Key, "attachment_id", true) == 0)
    //                {
    //                    attachment_id = int.Parse(kv.Value);
    //                }
    //                else if (string.Compare(kv.Key, "part_id", true) == 0)
    //                {
    //                    part_id = int.Parse(kv.Value);
    //                }

    //            }
    //            //删除硬盘上的附件
    //            DelectAttachmentFile(attachment_id);
    //        }

    //        strSql = string.Format("delete from  {0} where {1}", tableName, sbWhere);
    //        listSqls.Add(strSql);

    //        strSql = string.Format(@"IF (select count(*)  from partinfo a 
    //                                   inner join  attachment b on  a.part_id=b.part_id 
    //                                   where a.part_id = {0} )=0
    //                           update partinfo set is_attachment = 0   where part_id ={1}", part_id, part_id);
    //        listSqls.Add(strSql);

    //        try
    //        {
    //            DbHelperSQL.ExecuteSqlTran(listSqls);
    //            return true;
    //        }
    //        catch (Exception ex)
    //        {
    //            return false;
    //        }

    //    }

    //    /// <summary>
    //    /// 删除
    //    /// </summary>
    //    /// <param name="attachment_id">附件表attachment的id</param>
    //    /// <returns></returns>
    //    private bool DelectAttachmentFile(int attachment_id)
    //    {
    //        if (attachment_id <= 0)
    //        {
    //            return false;
    //        }

    //        BLL.Attachment bll = new BLL.Attachment();
    //        Becom.Model.Attachment model = bll.GetModel(attachment_id);
    //        string filePath = Server.MapPath("~") + model.attachment_path;
    //        try
    //        {
    //            System.IO.File.Delete(filePath);
    //            return true;
    //        }
    //        catch (Exception ex)
    //        {
    //            return false;
    //        }
    //    }

    //    /// <summary>
    //    /// 删除某个记录袋的所有文件
    //    /// </summary>
    //    /// <param name="part_id"></param>
    //    /// <returns></returns>
    //    private bool DelectAttachmentFiles(int part_id)
    //    {
    //        if (part_id <= 0)
    //        {
    //            return false;
    //        }

    //        BLL.Attachment bll = new BLL.Attachment();
    //        List<Becom.Model.Attachment> listModels = bll.GetModelList("part_id = " + part_id.ToString());
    //        foreach (Becom.Model.Attachment m in listModels)
    //        {
    //            string filePath = Server.MapPath("~") + m.attachment_path;
    //            try
    //            {
    //                System.IO.File.Delete(filePath);
    //            }
    //            catch (Exception ex)
    //            {
    //                return false;
    //            }
    //        }
    //        return false;
    //    }

    //    /// <summary>
    //    /// 获取某科目的评价
    //    /// </summary>
    //    /// <returns></returns>
    //    private DataSet GetSubjectAppraisal()
    //    {
    //        if (dictWheres == null || dictWheres.Count <= 0)
    //        {
    //            throw new Exception("Ajax参数错误.");
    //        }

    //        StringBuilder sbWhere = new StringBuilder();
    //        LinkString(dictWheres, "and", ref sbWhere);

    //        StringBuilder sbSql = new StringBuilder();
    //        sbSql.AppendFormat("select * from  {0} where {1}", tableName, sbWhere);

    //        return DbHelperSQL.Query(sbSql.ToString());
    //    }

    //    /// <summary>
    //    /// 获取科目返回字符串
    //    /// </summary>
    //    /// <param name="ds"></param>
    //    /// <returns></returns>
    //    private string GetXMLOfSubjectAppraisal(DataSet ds)
    //    {
    //        StringBuilder sbAppraisal = new StringBuilder();
    //        sbAppraisal.Append("<?xml version='1.0' encoding='GB2312'?>");  //
    //        sbAppraisal.AppendFormat("<{0}>", tableName);
    //        if (DbHelperSQL.DataSetIsEmpty(ds))
    //        {
    //            sbAppraisal.Append("<part_id>0</part_id>");
    //        }
    //        else
    //        {
    //            DataRow dr = ds.Tables[0].Rows[0];
    //            foreach (DataColumn dc in ds.Tables[0].Columns)
    //            {
    //                sbAppraisal.AppendFormat("<{0}>{1}</{2}>", dc.ColumnName.ToLower(), dr[dc.ColumnName], dc.ColumnName.ToLower());
    //            }
    //        }
    //        sbAppraisal.AppendFormat("</{0}>", tableName);
    //        return sbAppraisal.ToString();
    //    }


    private void LinkString(Dictionary<string, string> dict, string seperator, ref StringBuilder sb)
    {

        int i = 0;
        foreach (KeyValuePair<string, string> field in dict)
        {
            string value = string.Empty;
            if (string.Compare(field.Key, "createDate", true) != 0)
            {
                value = field.Value;
            }
            else  //创建时间重新获取
            {
                value = "'" + DateTime.Now.ToString() + "'";
            }

            if (i != 0)
            {
                sb.AppendFormat(" {0} {1}={2} ", seperator, field.Key, value);
            }
            else
            {
                sb.AppendFormat(" {0}={1} ", field.Key, value);
            }

            i++;
        }

    }

    /// <summary>
    /// 在字符串的两端添加单引号
    /// </summary>
    /// <param name="value"></param>
    private string AddSingleQuotes(string value)
    {
        string val = string.Format("'{0}'", value);
        return val;
    }
}